const fs = require('fs'),
    express = require('express'),
    app = express(),
    untils = require( "./Lib/utils" ),
    HOST = "http://localhost:8088/releases/",
    c = require('chalk'),
    cache = new Set();

fs.watch( "releases", { encoding: "utf8" }, ( eventType, filename ) => {
  const re = /\.exe$/i;
  if ( !filename || cache.has( filename ) || !re.test( filename ) ) {
    return;
  }
  cache.add( filename );
  const version = untils.getVersion( filename );
  if ( !version ){
    return;
  }
  untils.updateManifest( HOST, version );
});

app.get('/', function (req, res) {
  res.send('Hello!!!');
});

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  console.log( c.cyan( `${req.method} ${req.url}` ) );
  next();
});

app.use( express.static( "releases" ) ); //托管静态文件，就可以直接访问这个文件夹下的文件了
app.use( express.static( "." ) );  //可以直访问server下所有的文件

app.listen(8088, () => {
  console.log( `${c.yellow("Starting up release-server. Available on:")} ${c.green("http://127.0.0.1:8088")}` )
});